#coding=utf-8

#导入Python标准日志模块
import logging
import os 
from progressbar import * 
from urllib import request
import time  
import requests
import threading
#从Python SDK导入BOS配置管理模块以及安全认证模块
from baidubce.bce_client_configuration import BceClientConfiguration
from baidubce.auth.bce_credentials import BceCredentials
import pathlib
from hashlib import md5 as hash_
#导入BOS相关模块
from baidubce import exception
from baidubce.services import bos
from baidubce.services.bos import canned_acl
from baidubce.services.bos.bos_client import BosClient

#设置BosClient的Host，Access Key ID和Secret Access Key
from secret import *

#设置日志文件的句柄和日志级别
logger = logging.getLogger('baidubce.http.bce_http_client')
fh = logging.FileHandler("sample.log")
fh.setLevel(logging.DEBUG)

#设置日志文件输出的顺序、结构和内容
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.addHandler(fh)

#创建BceClientConfiguration
config = BceClientConfiguration(credentials=BceCredentials(access_key_id, secret_access_key), endpoint = bos_host)
    


#新建BosClient
bos_client = BosClient(config)
response = bos_client.list_buckets()

'''

response = bos_client.list_objects('zthubo')
for object in response.contents:
    print (object.key)
'''
#tgf.start()


bucket_name='zthubo'
object_key='Autosave-2.rws'
filePath="d:/temp/temp.tmp"

widgets = [Percentage(), ' ', Bar('#'),' ', Timer(),  ' ', ETA(), ' ', FileTransferSpeed()]

def cbk(a,b,c):
    '''回调函数
    @a:已经下载的数据块
    @b:数据块的大小
    @c:远程文件的大小
    '''
    global pbar
    if(c<a*b) :
        pbar.update(c)
        pbar.finish()  
    else:
        pbar.update(a*b)


def getFile(object_key,filePath):
    global pbar
    
    url = bos_client.generate_pre_signed_url(bucket_name, object_key,)
    print(url.decode('utf-8'))
    r = requests.get(url, stream=True)
    print("正在下载:",object_key)
    pbar = ProgressBar(widgets=widgets, maxval=int(r.headers['content-length'])).start()  
    dirpath=pathlib.Path(filePath).parent
    if(dirpath.is_dir()==False): dirpath.mkdir(parents=True)
    request.urlretrieve(url.decode('utf-8'),filePath,cbk)
def putFile(file_name,object_key):
    upload_id = bos_client.initiate_multipart_upload(bucket_name, object_key).upload_id

    left_size = os.path.getsize(file_name)
    # left_size用于设置分块开始位置
    # 设置分块的开始偏移位置
    offset = 0
    part_number = 1
    part_list = []
    file=open(file_name,"rb")
    print("正在上传: " , object_key)
    pbar = ProgressBar(widgets=widgets, maxval=left_size).start()  
    while left_size > 0:
        # 设置每块为5MB
        part_size = 1024*1024
        if left_size < part_size:
            part_size = left_size

        response = bos_client.upload_part_from_file(
            bucket_name, object_key, upload_id, part_number, part_size, file_name, offset)
        hash = hash_()
        data = file.read(part_size)
        hash.update(data)
        if(hash.hexdigest().upper()!=response.metadata.etag.upper()):
            logging.error("文件校验错误！")
            bos_client.abort_multipart_upload(bucket_name, object_key, upload_id)
            print(("文件校验错误！"))

        left_size -= part_size
        offset += part_size
        part_list.append({
            "partNumber": part_number,
            "eTag": response.metadata.etag
        })

        part_number += 1
        pbar.update(offset)

    bos_client.complete_multipart_upload(bucket_name, object_key, upload_id, part_list)
    pbar.finish()  
    file.close()

def getHash(filepath):
    if(os.path.isfile(filepath)):
        size = os.path.getsize(filepath)
        # print(file,size)
        try:
            file = open(filepath, "rb")
        except:
            logging.error("can't open file!")
            return "fail!"
        hash = hash_()
        n = 0
        bs = 1024*1024*32
        while True :
            # 处理该行的代码
            data = file.read(bs)
            if(len(data) == 0):
                break
            hash.update(data)
        file.close()
        return hash.hexdigest()
        # return hash.hexdigest()
    else:
        logging.error("error")

'''
getFile('Autosave-1.rws',"d:/temp/123/123/1/Autosave-1.rws")
getFile(object_key,filePath)

print(getHash(os.path.expanduser('~/AppData/LocalLow/Ludeon Studios/RimWorld by Ludeon Studios/Saves/Autosave-2.rws')))
print(getHash(filePath))
putFile(os.path.expanduser('~/AppData/LocalLow/Ludeon Studios/RimWorld by Ludeon Studios/Saves/Autosave-3.rws'),"Saves/Autosave-3.rws")
'''

